<!-- templates/accounts/login.html -->
{% extends 'base.html' %}

{% block title %}登录 - AI故事生成器{% endblock %}

{% block content %}
<div class="auth-container">
    <h1>用户登录</h1>
    <div id="login-message" class="message"></div>
    <form id="loginForm" class="auth-form" onsubmit="return handleLogin(event)">
        {% csrf_token %}
        <!-- 支持next参数重定向 -->
        {% if request.GET.next %}
            <input type="hidden" name="next" value="{{ request.GET.next }}">
        {% endif %}
        <div class="form-group">
            <label for="identifier">用户名或邮箱</label>
            <input type="text" id="identifier" name="identifier" placeholder="请输入用户名或邮箱" required>
        </div>
        
        <div class="form-group">
            <label for="password">密码</label>
            <input type="password" id="password" name="password" placeholder="请输入密码" required>
        </div>
        
        <button type="submit" class="btn">登录</button>
    </form>
    
    <p class="auth-switch">
        还没有账户？<a href="{% url 'user:register' %}">立即注册</a>
    </p>
</div>

<script>
function handleLogin(event) {
    event.preventDefault();
    console.log('登录表单提交');
    
    const messageEl = document.getElementById('login-message');
    const identifier = document.getElementById('identifier').value;
    const password = document.getElementById('password').value;
    
    // 简单的前端验证
    if (!identifier || !password) {
        showMessage(messageEl, '请填写所有字段', 'error');
        return false;
    }
    
    // 显示加载状态
    const submitButton = document.querySelector('#loginForm button[type="submit"]');
    const originalText = submitButton.textContent;
    submitButton.textContent = '登录中...';
    submitButton.disabled = true;
    
    // 收集表单数据
    const formData = new FormData(document.getElementById('loginForm'));
    
    // 发送登录请求
    fetch('/user/login/', {
        method: 'POST',
        body: formData,
        headers: {
            'X-CSRFToken': getCSRFToken()
        }
    })
    .then(response => response.json())
    .then(data => {
        console.log('登录响应:', data);
        if (data.success) {
            showMessage(messageEl, data.message, 'success');
            setTimeout(() => {
                // 使用后端返回的重定向URL，默认为首页
                window.location.href = data.next_url || '/index/';
            }, 1000);
        } else {
            showMessage(messageEl, data.message, 'error');
        }
    })
    .catch(error => {
        console.error('登录错误:', error);
        showMessage(messageEl, '登录过程中发生错误，请稍后重试', 'error');
    })
    .finally(() => {
        // 恢复按钮状态
        submitButton.textContent = originalText;
        submitButton.disabled = false;
    });
    
    return false;
}

function showMessage(element, message, type) {
    element.textContent = message;
    element.className = 'message ' + type;
    element.style.display = 'block';
    
    // 3秒后自动隐藏成功消息
    if (type === 'success') {
        setTimeout(() => {
            element.style.display = 'none';
        }, 3000);
    }
}

function getCSRFToken() {
    // 从表单中获取CSRF token
    const csrfInput = document.querySelector('input[name="csrfmiddlewaretoken"]');
    if (csrfInput) {
        return csrfInput.value;
    }
    // 从 cookie中获取
    return getCookie('csrftoken');
}

function getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        const cookies = document.cookie.split(';');
        for (let i = 0; i < cookies.length; i++) {
            const cookie = cookies[i].trim();
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}
</script>
{% endblock %}